import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_easylogger/flutter_logger.dart';
import '../../../../config/router_page_name.dart';
import '../../../../models/category_model.dart';
import '../../../../http/http_service.dart';
import '../../../../utils/user_info_utils.dart';
import '../../logic.dart';

class ConfirmOrderLogic extends GetxController {
  // 购物车商品
  late List<CartItem> cartItems;

  // 总价
  late double totalPrice;

  // 选择的地址
  final selectedAddress = ''.obs;
  final selectedAddressDetail = ''.obs;

  // 备注控制器
  late TextEditingController remarkController;

  // 主题颜色
  final Color primaryColor = Color(0xFF6A5ACD);
  final Color lightColor = Color(0xFFE6E6FA);

  // HTTP服务
  final httpService = HttpService();

  @override
  void onInit() {
    super.onInit();

    final args = Get.arguments;
    cartItems = args['cartItems'];
    totalPrice = args['totalPrice'];

    Logger.d('确认订单初始化: ${cartItems.length}个商品, 总价${totalPrice}');

    remarkController = TextEditingController();
  }

  @override
  void onClose() {
    remarkController.dispose();
    super.onClose();
  }

  // 选择地址
  void selectAddress() {
    final nameController = TextEditingController(text: selectedAddress.value);
    final phoneController = TextEditingController();
    final addressController = TextEditingController(text: selectedAddressDetail.value);

    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
        ),
        child: Container(
          padding: EdgeInsets.all(20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Center(
                child: Text(
                  '添加收货地址',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: primaryColor,
                  ),
                ),
              ),
              SizedBox(height: 20),
              TextField(
                controller: nameController,
                decoration: InputDecoration(
                  labelText: '收货人',
                  hintText: '请输入收货人姓名',
                  filled: true,
                  fillColor: lightColor,
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                    borderSide: BorderSide.none,
                  ),
                  prefixIcon: Icon(Icons.person, color: primaryColor),
                ),
              ),
              SizedBox(height: 15),
              TextField(
                controller: phoneController,
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                  labelText: '手机号',
                  hintText: '请输入收货人手机号',
                  filled: true,
                  fillColor: lightColor,
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                    borderSide: BorderSide.none,
                  ),
                  prefixIcon: Icon(Icons.phone, color: primaryColor),
                ),
              ),
              SizedBox(height: 15),
              TextField(
                controller: addressController,
                decoration: InputDecoration(
                  labelText: '详细地址',
                  hintText: '请输入详细地址',
                  filled: true,
                  fillColor: lightColor,
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                    borderSide: BorderSide.none,
                  ),
                  prefixIcon: Icon(Icons.location_on, color: primaryColor),
                ),
              ),
              SizedBox(height: 25),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  OutlinedButton(
                    onPressed: () => Get.back(),
                    style: OutlinedButton.styleFrom(
                      side: BorderSide(color: primaryColor),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20),
                      ),
                      padding: EdgeInsets.symmetric(horizontal: 30, vertical: 12),
                    ),
                    child: Text(
                      '取消',
                      style: TextStyle(
                        color: primaryColor,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  ElevatedButton(
                    onPressed: () {
                      if (nameController.text.isEmpty || addressController.text.isEmpty) {
                        Get.snackbar(
                          '提示',
                          '请填写完整的地址信息',
                          backgroundColor: Colors.white,
                          colorText: Colors.black,
                          snackPosition: SnackPosition.TOP,
                        );
                        return;
                      }

                      // 保存地址信息
                      selectedAddress.value = nameController.text;
                      selectedAddressDetail.value = addressController.text;
                      Logger.d('设置收货地址: ${selectedAddress.value}, ${selectedAddressDetail.value}');
                      Get.back();
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: primaryColor,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20),
                      ),
                      padding: EdgeInsets.symmetric(horizontal: 30, vertical: 12),
                    ),
                    child: Text(
                      '确定',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 提交订单
  void submitOrder() {
    if (selectedAddress.isEmpty) {
      Get.snackbar(
        '提示',
        '请选择收货地址',
        backgroundColor: Colors.white,
        colorText: Colors.black,
        snackPosition: SnackPosition.TOP,
      );
      return;
    }

    // 检查用户ID
    var loginModel = DataUtils().getLoginModel();
    if (loginModel.id == null) {
      Get.snackbar(
        '提示',
        '未获取到用户信息，请重新登录',
        backgroundColor: Colors.white,
        colorText: Colors.black,
        snackPosition: SnackPosition.TOP,
      );
      return;
    }

    // 支付对话框
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
        ),
        child: Container(
          padding: EdgeInsets.all(20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.payment,
                size: 60,
                color: primaryColor,
              ),
              SizedBox(height: 15),
              Text(
                '支付订单',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(height: 10),
              Text(
                '订单总金额：¥${(totalPrice + 5.0).toStringAsFixed(2)}',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Colors.red,
                ),
              ),
              SizedBox(height: 5),
              Text(
                '请选择支付方式完成订单',
                style: TextStyle(
                  color: Colors.grey[600],
                ),
              ),
              SizedBox(height: 25),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  _buildPaymentOption(
                    icon: Icons.attach_money,
                    title: '校园卡',
                    onTap: _paymentSuccess,
                  ),
                  _buildPaymentOption(
                    icon: Icons.payment,
                    title: '支付宝',
                    onTap: _paymentSuccess,
                  ),
                  _buildPaymentOption(
                    icon: Icons.wallet,
                    title: '微信',
                    onTap: _paymentSuccess,
                  ),
                ],
              ),
              SizedBox(height: 20),
              OutlinedButton(
                onPressed: () => Get.back(),
                style: OutlinedButton.styleFrom(
                  side: BorderSide(color: Colors.grey),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                  padding: EdgeInsets.symmetric(horizontal: 30, vertical: 10),
                ),
                child: Text('取消支付'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 支付选项
  Widget _buildPaymentOption({
    required IconData icon,
    required String title,
    required Function onTap,
  }) {
    return InkWell(
      onTap: () {
        Get.back();
        onTap();
      },
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: lightColor,
              shape: BoxShape.circle,
            ),
            child: Icon(
              icon,
              color: primaryColor,
              size: 24,
            ),
          ),
          SizedBox(height: 8),
          Text(
            title,
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  // 支付成功 - 创建订单
  void _paymentSuccess() async {
    Logger.d('开始创建订单流程');

    // 显示加载对话框
    Get.dialog(
      Center(
        child: CircularProgressIndicator(
          color: Colors.white,
        ),
      ),
      barrierDismissible: false,
    );

    try {
      // 获取用户ID
      var loginModel = DataUtils().getLoginModel();
      var userId = loginModel.id;
      Logger.d('当前用户ID: $userId');

      // 准备订单数据
      final orderItems = cartItems.map((item) => {
        'foodId': item.food.id,
        'quantity': item.quantity,
      }).toList();

      final orderData = {
        'userId': userId, // 传递用户ID
        'totalPrice': totalPrice + 5.0, // 加上配送费
        'address': selectedAddress.value,
        'addressDetail': selectedAddressDetail.value,
        'remark': remarkController.text,
        'items': orderItems,
      };

      Logger.d('提交订单数据: $orderData');

      // 发送创建订单请求
      final response = await httpService.post('/orders', data: orderData);

      // 关闭加载对话框
      Get.back();

      if (response.statusCode == 200) {
        Logger.i('订单创建成功');

        // 显示支付成功对话框
        Get.dialog(
          Dialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20),
            ),
            child: Container(
              padding: EdgeInsets.all(20),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    padding: EdgeInsets.all(15),
                    decoration: BoxDecoration(
                      color: Colors.green.withOpacity(0.1),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      Icons.check_circle,
                      color: Colors.green,
                      size: 60,
                    ),
                  ),
                  SizedBox(height: 20),
                  Text(
                    '支付成功',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(height: 10),
                  Text(
                    '您的订单已支付成功，请耐心等待送达',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.grey[600],
                    ),
                  ),
                  SizedBox(height: 25),
                  ElevatedButton(
                    onPressed: () {
                      Get.back();
                      Get.offAllNamed(RouterPageName.appPage);
                      Future.delayed(Duration(milliseconds: 300), () {
                        final appLogic = Get.find<AppLogic>();
                        appLogic.changePage(2); // 切换到订单页面
                      });
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: primaryColor,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(25),
                      ),
                      minimumSize: Size(200, 45),
                    ),
                    child: Text(
                      '查看订单',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          barrierDismissible: false,
        );
      } else {
        String errorMessage = response.data['message'] ?? "创建订单失败，请重试";
        Logger.e('创建订单失败: $errorMessage');

        Get.snackbar(
          '下单失败',
          errorMessage,
          backgroundColor: Colors.white70,
          snackPosition: SnackPosition.TOP,
          duration: Duration(seconds: 3),
        );
      }
    } catch (e) {
      // 关闭加载对话框
      Get.back();

      Logger.e('创建订单异常: $e');

      // 显示错误提示
      Get.snackbar(
        '下单失败',
        '创建订单失败，请重试: $e',
        backgroundColor: Colors.white70,
        snackPosition: SnackPosition.TOP,
        duration: Duration(seconds: 3),
      );
    }
  }
}